import 'dart:async';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:www.znpigai.teacher/utils/pay_dialog.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Widget buildView(
    PayListState state, Dispatch dispatch, ViewService viewService) {
  final ListAdapter adapter = viewService.buildAdapter();
  final ScrollController _scrollController = new ScrollController();
  _scrollController.addListener(() {
    // 如果下拉的当前位置到scroll的最下面
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      dispatch(PayListActionCreator.onLoad());
    }
  });

  void showPayDialog(Dispatch dispatch, BuildContext context) async {
    if (state.buttonText == '初始化失败') {
      Util.alert('请返回重试', context);
      return;
    } else if (state.buttonText == '连接中，请稍候...') {
      Util.alert('请稍候...', context);
      return;
    }

    String result = await showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return PayDialog(state.products, state.purchases);
      },
    );

    if (result != null) {
      dispatch(PayListActionCreator.onPay(result));
    }
  }

  bool isMember() {
    return state.userInfo.containsKey('accountInfo') &&
        (state.userInfo['accountInfo']['validRechargeUser'] ||
            state.userInfo['accountInfo']['validBillingCardUser']);
  }

  String memberString() {
    if (isMember()) {
      String time = state.userInfo['accountInfo']['rechargeExpiryTime'];
      if (time == null || time.isEmpty) {
        time = state.userInfo['accountInfo']['billingCardExpiryDate'] ?? '';
      }
      return "会员到期时间：$time";
    } else {
      return '您还不是会员哦！';
    }
  }

  List<Widget> _listView() {
    var widgets = <Widget>[];
    if (adapter.itemCount == 0) {
      if (!state.isLoading) {
        widgets.add(Center(
            child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Image.asset("assets/images/empty.png",
                width: 150, fit: BoxFit.fill),
            Text('没有充值记录', style: TextStyle(color: Colors.grey))
          ],
        )));
      }
    } else {
      widgets.add(ListView.separated(
        physics: AlwaysScrollableScrollPhysics(),
        // work when several items
        itemBuilder: (context, index) {
          if (index == adapter.itemCount) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: new Center(
                child: new Opacity(
                  opacity: state.isLoading ? 0.0 : 1.0,
                  child: Text(index != 0 ? '没有更多了' : '',
                      style: TextStyle(color: Colors.grey)),
                ),
              ),
            );
          } else {
            return adapter.itemBuilder(context, index);
          }
        },
        itemCount: adapter.itemCount + 1,
        controller: _scrollController,
        separatorBuilder: (context, index) {
          return Divider(height: 1);
        },
      ));
    }

    if (state.isLoading) {
      widgets.add(Center(
          child: SizedBox(
              width: 110,
              height: 110,
              child: Card(
                  key: null,
                  color: Colors.black45,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      SpinKitFadingCircle(
                        color: Colors.blue,
                        size: 50,
                      ),
                      Padding(
                        padding: const EdgeInsets.only(
                          top: 20.0,
                        ),
                        child: new Text(
                          "正在加载...",
                          style: TextStyle(fontSize: 12.0, color: Colors.white),
                        ),
                      ),
                    ],
                  )))));
    }

    return widgets;
  }

  return Scaffold(
    appBar: AppBar(
      centerTitle: true,
      backgroundColor: state.themeColor,
      title: const Text('会员充值'),
    ),
    body: Column(
      children: <Widget>[
        SizedBox(height: 10),
        Container(
          width: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/member_bg.png"),
              fit: BoxFit.fill,
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              SizedBox(height: 30),
              Text(memberString(), style: TextStyle(color: Colors.white)),
              SizedBox(height: 20),
              FlatButton(
                textColor: Colors.white,
                padding: const EdgeInsets.all(0.0),
                child: Container(
                  decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        colors: <Color>[
                          Colors.orange,
                          Colors.yellow,
                        ],
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(80.0))),
                  padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
                  child: Text(state.buttonText,
                      style: TextStyle(color: Colors.white)),
                ),
                onPressed: () {
                  showPayDialog(dispatch, viewService.context);
                },
              ),
              SizedBox(height: 30),
            ],
          ),
        ),
        Expanded(
          child: RefreshIndicator(
            child: Column(
              children: <Widget>[
                Expanded(
                  child: Stack(
                    children: _listView(),
                  ),
                ),
              ],
            ),
            onRefresh: () {
              final Completer<void> completer = Completer<void>();
              dispatch(
                  PayListActionCreator.onReload(() => completer.complete()));
              return completer.future;
            },
          ),
        )
      ],
    ),
  );
}
